const OSS = require('ali-oss')
import { oss_sts, get_oss_key } from '@/api/API_get_ossKey'
import { oss_sts_path } from '@/mylibs/define'

var usenum = 1

const headers = {
  'x-oss-forbid-overwrite': 'false'
}

// 处理请求失败的情况，防止promise.all中断，并返回失败原因和失败文件名。
async function handleDel(name, options) {
  try {
    await client.delete(name)
  } catch (error) {
    error.failObjectName = name
    return error
  }
}

async function putBuffer(method, name, data, isfile, fun_back) {
  if (usenum == 1) {
    await get_oss_key()
    usenum++
  }
  // 在客户端使用临时访问凭证初始化OSS客户端，用于临时授权访问OSS资源。
  const client = new OSS({
    // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
    region: 'oss-cn-beijing',
    accessKeyId: oss_sts.AccessKeyId,
    accessKeySecret: oss_sts.AccessKeySecret,
    stsToken: oss_sts.SecurityToken,
    // yourbucketname填写存储空间名称。
    bucket: '18085583045',
    // 刷新临时访问凭证。
    refreshSTSToken: async function get_oss_key() {
      let { data: respose } = await axios.get(oss_sts_path)
      // console.log(respose)
      if (respose.ret != 0) {
        alert('获取oss sts 失败:' + respose.msg)
        return
      }
      let obj = JSON.parse(respose.res)
      // console.log(obj)
      return {
        accessKeyId: obj.Credentials.AccessKeyId,
        accessKeySecret: obj.Credentials.AccessKeySecret,
        stsToken: obj.Credentials.SecurityToken
      }
    }
  })

  try {
    var result = {
      res: null,
      ok: true,
      err: null
    }
    // 提交数据
    if (method == 'put' || method == 'PUT') {
      console.log('api:put', data)
      // 条件判断
      if (!data) {
        console.log('putBuffer err:数据为空')
        result.err = 'data数据为空'
        result.ok = false
      }
      if (isfile) {
        var res = await client.put(name, data, { headers }).catch((e) => {
          // console.log(1)
          console.log(e)
          result.ok = false
          result.err = e
        })
      } else {
        // {}对象转json字符
        var jsonstr = JSON.stringify(data)
        // console.log(jsonstr)

        // 字符转blob
        var blob = new Blob([jsonstr], { type: 'text/plain' })
        var res = await client.put(name, blob, { headers }).catch((e) => {
          console.log(e)

          result.ok = false
          result.err = e
        })
      }
      if (fun_back) {
        fun_back(res)
      }
      // console.log(2)
      if (res) result.res = res.url
    }
    // 获取数据
    else if (method == 'get' || method == 'GET') {
      var res = await client.get(name).catch((e) => {
        console.log(e)
        result.ok = false
        result.err = e
      })
      if (res) {
        if (isfile) {
          console.log('api:get', res)
          result.res = res.content
        } else {
          var fileData = res.content

          // Uint8Array转字符串
          var utf8decoder = new TextDecoder()
          var dataString = utf8decoder.decode(fileData)

          // console.log(dataString)
          // JSON字符串转化 对象
          var jsonObject = JSON.parse(dataString)
          if (fun_back) {
            fun_back(res)
          }
          console.log('api:get', jsonObject)

          result.res = jsonObject
        }
      }
    } else if (method == 'del' || method == 'DEL') {
      var res = await client.delete(name, { quiet: true }).catch((e) => {
        console.log(e)
        result.ok = false
        result.err = e
      })
      if (fun_back) {
        fun_back(result)
      }

      result.res = res
    } else if (method == 'rename') {
      // 将srcobject.txt拷贝至同一Bucket下的destobject.txt。新的,旧的
      // client.copy('destobject.txt', 'srcobject.txt')
      client
        .copy(name.newname, name.oldname)
        .then((r) => {
          client
            // 删除srcobject.txt。
            .delete(name.oldname)
            .then((res) => {
              if (fun_back) {
                fun_back(res)
              }

              result.res = res
            })
            .catch((e) => {
              console.log(e)
              result.ok = false
              result.err = e
            })
        })
        .catch((e) => {
          result.ok = false
          result.err = e
        })
    } else if (method == 'deldir') {
      if (name == '' || name == null) {
        return { ok: false, res: 'name为空' }
      }

      var list = await client.list({
        prefix: name
      })

      list.objects = list.objects || []
      var res = await Promise.all(
        list.objects.map((v) => handleDel(v.name))
      ).catch((e) => {
        console.log(e)
        result.ok = false
        result.err = e
      })

      if (fun_back) {
        fun_back(res)
      }
      result.res = res
    }

    console.log(3)
    return result
  } catch (e) {
    console.log(e)
    return {
      ok: false,
      res: null,
      err: e
    }
  }
}

export default putBuffer
